package com.atguigu.rabbitmq.springbootrabbitmq.controller;

import com.atguigu.rabbitmq.springbootrabbitmq.config.DelayedQueueConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author gan
 * @create 2021-07-25 15:57
 *
 * 发送延迟消息
 *
 * http://localhost:8080/ttl/sendMsg/嘻嘻嘻
 */

@Slf4j
@RestController
@RequestMapping("/ttl")
public class SendMsgController {

    @Resource
    private RabbitTemplate rabbitTemplate;

    //开始发消息
    @GetMapping("/sendMsg/{message}")
    public void sendMsg(@PathVariable String message){

//        System.out.println("当前时间：" + new Date().toString() + ", 发送一条信息给两个TTl队列：" + message);
        log.info("当前时间：{}，发送一条信息给两个ttl队列：{}，", new Date().toString(), message);

        rabbitTemplate.convertAndSend("X", "XA", "消息来自ttl为10s的队列：" + message);
        rabbitTemplate.convertAndSend("X", "XB", "消息来自ttl为40s的队列：" + message);
    }

    // http://localhost:8080/ttl/sendExpirationMsg/你好1/20000
    // http://localhost:8080/ttl/sendExpirationMsg/你好2/2000

    //开始发消息  消息TTL
    @GetMapping("/sendExpirationMsg/{message}/{ttlTime}")
    public void sendMsg(@PathVariable String message, @PathVariable String ttlTime){
//        System.out.println("当前时间：" + new Date().toString() + "，发送一条时长：" + ttlTime + " 毫秒TTL信息给队列QC：" + message);
        log.info("当前时间：{}，发送一条时长{}毫秒的信息给队列QC：{}", new Date().toString(), ttlTime, message);

        rabbitTemplate.convertAndSend("X", "XC", message, msg-> {
            //发送消息的时候   延迟时长
            msg.getMessageProperties().setExpiration(ttlTime);
            return msg;
        });
    }

    /*
    http://localhost:8080/ttl/sendDelayMsg/helloworld1/20000
    http://localhost:8080/ttl/sendDelayMsg/helloworld2/2000
     */

    //开始发送消息 基于插件的  消息及延迟的时间
    @GetMapping("/sendDelayMsg/{message}/{delayTime}")
    public void sendMsg(@PathVariable String message, @PathVariable Integer delayTime){
//        System.out.println("当前时间：" + new Date().toString() + "，发送一条时长：" + delayTime + " 毫秒信息给延迟队列delayed.queue：" + message);
        log.info("当前时间：{}，发送一条时长{}毫秒的信息给延时队列delayed.queue：{}", new Date().toString(), delayTime, message);
        rabbitTemplate.convertAndSend(DelayedQueueConfig.DELAYED_EXCHANGE_NAME, DelayedQueueConfig.DELAYED_ROUTING_KEY, message, msg -> {
            //发送消息的时候  延迟时长  msg
            msg.getMessageProperties().setDelay(delayTime);
            return msg;
        });
    }
}
